import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 用户信息
  const userInfo = ref({
    uid: '',
    userId: '',
    userName: '',
    userType: '',
    phoneNumber: '',
    email: '',
    isAdmin: false
  })
  
  // token信息
  const token = ref('')
  const refreshToken = ref('')
  const expiresIn = ref(0)
  
  // 设置token信息
  function setToken(tokenInfo) {
    token.value = tokenInfo.accessToken
    refreshToken.value = tokenInfo.refreshToken
    expiresIn.value = tokenInfo.expiresIn
    
    // 保存到localStorage
    localStorage.setItem('token', token.value)
    localStorage.setItem('refreshToken', refreshToken.value)
    localStorage.setItem('expiresIn', expiresIn.value)
  }
  
  // 设置用户信息
  function setUserInfo(info) {
    userInfo.value = {
      ...userInfo.value,
      ...info
    }
    
    // 保存到localStorage
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  }
  
  // 从localStorage恢复状态
  function restoreState() {
    const storedToken = localStorage.getItem('token')
    const storedRefreshToken = localStorage.getItem('refreshToken')
    const storedExpiresIn = localStorage.getItem('expiresIn')
    const storedUserInfo = localStorage.getItem('userInfo')
    
    if (storedToken) token.value = storedToken
    if (storedRefreshToken) refreshToken.value = storedRefreshToken
    if (storedExpiresIn) expiresIn.value = parseInt(storedExpiresIn)
    if (storedUserInfo) userInfo.value = JSON.parse(storedUserInfo)
  }
  
  // 清除用户状态
  function clearState() {
    token.value = ''
    refreshToken.value = ''
    expiresIn.value = 0
    userInfo.value = {
      uid: '',
      userId: '',
      userName: '',
      userType: '',
      phoneNumber: '',
      email: '',
      isAdmin: false
    }
    
    // 清除localStorage
    localStorage.removeItem('token')
    localStorage.removeItem('refreshToken')
    localStorage.removeItem('expiresIn')
    localStorage.removeItem('userInfo')
  }
  
  // 初始化时恢复状态
  restoreState()
  
  return {
    userInfo,
    token,
    refreshToken,
    expiresIn,
    setToken,
    setUserInfo,
    clearState
  }
}) 